{
 "cells": [
  {
   "cell_type": "code",
   "id": "53fd1231",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T13:10:38.029199Z",
     "start_time": "2025-05-23T13:10:26.902267Z"
    }
   },
   "source": [
    "import torch\n",
    "from torchvision.models import AlexNet\n",
    "import netron\n",
    "\n",
    "model = AlexNet()\n",
    "\n",
    "input = torch.ones((1,3,224,224))\n",
    "\n",
    "torch.onnx.export(model, input, f='AlexNet.onnx')   #导出 .onnx 文件\n",
    "netron.start('AlexNet.onnx') #展示结构图"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Serving 'AlexNet.onnx' at http://localhost:8080\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('localhost', 8080)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T13:18:24.341841Z",
     "start_time": "2025-05-23T13:18:22.365688Z"
    }
   },
   "cell_type": "code",
   "source": "pip list",
   "id": "864b449197214db8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Package                   Version\n",
      "------------------------- --------------\n",
      "absl-py                   2.2.2\n",
      "anyio                     4.9.0\n",
      "argon2-cffi               23.1.0\n",
      "argon2-cffi-bindings      21.2.0\n",
      "arrow                     1.3.0\n",
      "asttokens                 3.0.0\n",
      "async-lru                 2.0.5\n",
      "attrs                     25.3.0\n",
      "babel                     2.17.0\n",
      "backcall                  0.2.0\n",
      "beautifulsoup4            4.13.4\n",
      "bleach                    6.2.0\n",
      "certifi                   2025.4.26\n",
      "cffi                      1.17.1\n",
      "charset-normalizer        3.4.2\n",
      "colorama                  0.4.6\n",
      "comm                      0.2.1\n",
      "debugpy                   1.8.11\n",
      "decorator                 5.1.1\n",
      "defusedxml                0.7.1\n",
      "exceptiongroup            1.2.0\n",
      "executing                 0.8.3\n",
      "fastjsonschema            2.21.1\n",
      "filelock                  3.18.0\n",
      "fqdn                      1.5.1\n",
      "fsspec                    2025.5.0\n",
      "graphviz                  0.20.3\n",
      "grpcio                    1.71.0\n",
      "h11                       0.16.0\n",
      "httpcore                  1.0.9\n",
      "httpx                     0.28.1\n",
      "idna                      3.10\n",
      "importlib_metadata        8.5.0\n",
      "ipykernel                 6.29.5\n",
      "ipython                   8.15.0\n",
      "isoduration               20.11.0\n",
      "jedi                      0.19.2\n",
      "Jinja2                    3.1.6\n",
      "json5                     0.12.0\n",
      "jsonpatch                 1.33\n",
      "jsonpointer               3.0.0\n",
      "jsonschema                4.23.0\n",
      "jsonschema-specifications 2025.4.1\n",
      "jupyter_client            8.6.3\n",
      "jupyter_core              5.7.2\n",
      "jupyter-events            0.12.0\n",
      "jupyter-lsp               2.2.5\n",
      "jupyter_server            2.16.0\n",
      "jupyter_server_terminals  0.5.3\n",
      "jupyterlab                4.4.2\n",
      "jupyterlab_pygments       0.3.0\n",
      "jupyterlab_server         2.27.3\n",
      "Markdown                  3.8\n",
      "MarkupSafe                3.0.2\n",
      "matplotlib-inline         0.1.6\n",
      "mistune                   3.1.3\n",
      "mpmath                    1.3.0\n",
      "nbclient                  0.10.2\n",
      "nbconvert                 7.16.6\n",
      "nbformat                  5.10.4\n",
      "nest-asyncio              1.6.0\n",
      "netron                    8.3.4\n",
      "networkx                  3.2.1\n",
      "notebook                  7.4.2\n",
      "notebook_shim             0.2.4\n",
      "numpy                     2.0.2\n",
      "onnx                      1.18.0\n",
      "opencv-python             4.11.0.86\n",
      "overrides                 7.7.0\n",
      "packaging                 24.2\n",
      "pandocfilters             1.5.1\n",
      "parso                     0.8.4\n",
      "pickleshare               0.7.5\n",
      "pillow                    11.2.1\n",
      "pip                       25.1\n",
      "platformdirs              4.3.7\n",
      "prometheus_client         0.22.0\n",
      "prompt-toolkit            3.0.43\n",
      "protobuf                  6.31.0\n",
      "psutil                    5.9.0\n",
      "pure-eval                 0.2.2\n",
      "pycparser                 2.22\n",
      "Pygments                  2.19.1\n",
      "python-dateutil           2.9.0.post0\n",
      "python-json-logger        3.3.0\n",
      "pywin32                   308\n",
      "pywinpty                  2.0.15\n",
      "PyYAML                    6.0.2\n",
      "pyzmq                     26.2.0\n",
      "referencing               0.36.2\n",
      "requests                  2.32.3\n",
      "rfc3339-validator         0.1.4\n",
      "rfc3986-validator         0.1.1\n",
      "rpds-py                   0.25.1\n",
      "scipy                     1.13.1\n",
      "Send2Trash                1.8.3\n",
      "setuptools                78.1.1\n",
      "six                       1.17.0\n",
      "sniffio                   1.3.1\n",
      "soupsieve                 2.7\n",
      "stack-data                0.2.0\n",
      "sympy                     1.13.1\n",
      "tensorboard               2.19.0\n",
      "tensorboard-data-server   0.7.2\n",
      "tensorboardX              2.6.2.2\n",
      "terminado                 0.18.1\n",
      "tinycss2                  1.4.0\n",
      "tomli                     2.2.1\n",
      "torch                     2.6.0+cu124\n",
      "torchaudio                2.6.0+cu124\n",
      "torchvision               0.21.0+cu124\n",
      "torchviz                  0.0.3\n",
      "tornado                   6.4.2\n",
      "traitlets                 5.14.3\n",
      "types-python-dateutil     2.9.0.20250516\n",
      "typing_extensions         4.12.2\n",
      "uri-template              1.3.0\n",
      "urllib3                   2.4.0\n",
      "visdom                    0.2.4\n",
      "wcwidth                   0.2.5\n",
      "webcolors                 24.11.1\n",
      "webencodings              0.5.1\n",
      "websocket-client          1.8.0\n",
      "Werkzeug                  3.1.3\n",
      "wheel                     0.45.1\n",
      "zipp                      3.21.0\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "id": "b570baa8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T13:18:29.520885Z",
     "start_time": "2025-05-23T13:18:27.788859Z"
    }
   },
   "source": [
    "import math\n",
    "import netron\n",
    "import torch.onnx\n",
    "import torch.nn as nn\n",
    "from torch.autograd import Variable\n",
    "\n",
    "default_cfg = {\n",
    "    11 : [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],\n",
    "    13 : [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512],\n",
    "    16 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512],\n",
    "    19 : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512],}\n",
    "\n",
    "class vgg(nn.Module):\n",
    "    def __init__(self, dataset='cifar10', depth=19, init_weights=True, cfg=None):\n",
    "        super(vgg, self).__init__()\n",
    "        if cfg is None:\n",
    "            cfg = default_cfg[depth]\n",
    "\n",
    "        self.feature = self.make_layers(cfg, True)\n",
    "\n",
    "        if dataset == 'cifar10':\n",
    "            num_classes = 10\n",
    "        elif dataset == 'cifar100':\n",
    "            num_classes = 100\n",
    "        self.classifier = nn.Linear(cfg[-1], num_classes)\n",
    "        if init_weights:\n",
    "            self._initialize_weights()\n",
    "\n",
    "    def make_layers(self, cfg, batch_norm=False):\n",
    "        layers = []\n",
    "        in_channels = 3\n",
    "        for v in cfg:\n",
    "            if v == 'M':\n",
    "                layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n",
    "            else:\n",
    "                conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1, bias=False)\n",
    "                if batch_norm:\n",
    "                    layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n",
    "                else:\n",
    "                    layers += [conv2d, nn.ReLU(inplace=True)]\n",
    "                in_channels = v\n",
    "        return nn.Sequential(*layers)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.feature(x)\n",
    "        x = nn.AvgPool2d(2)(x)\n",
    "        x = x.view(x.size(0), -1)\n",
    "        y = self.classifier(x)\n",
    "        return y\n",
    "\n",
    "    def _initialize_weights(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv2d):\n",
    "                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n",
    "                m.weight.data.normal_(0, math.sqrt(2. / n))\n",
    "                if m.bias is not None:\n",
    "                    m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.weight.data.fill_(0.5)\n",
    "                m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.Linear):\n",
    "                m.weight.data.normal_(0, 0.01)\n",
    "                m.bias.data.zero_()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    net = vgg()\n",
    "    x = Variable(torch.FloatTensor(16, 3, 40, 40))\n",
    "    y = net(x)\n",
    "    print(y.data.shape)\n",
    "    onnx_path = \"onnx_model_name.onnx\"\n",
    "    torch.onnx.export(net, x, onnx_path)\n",
    "    netron.start(onnx_path)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([16, 10])\n",
      "Serving 'onnx_model_name.onnx' at http://localhost:8080\n"
     ]
    }
   ],
   "execution_count": 4
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch_stu",
   "language": "python",
   "name": "pytorch_stu"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
